package hibernate.method;

import hibernate.constraint.Constraint;
import hibernate.method.interfaces.MessageMethodsInterface;
import hibernate.model.Message;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

public class MessageMethods implements MessageMethodsInterface{

	@Override
	public void send(SessionFactory sessionFactory, Session session,
			int receiver_id, int sender_id, String subject, String content) {
		Message msg = new Message();
		msg.setReceiver_id(receiver_id);
		msg.setSender_id(sender_id);
		msg.setSend_date(AdditionalMethods.getCurrentDate());
		msg.setSend_time(AdditionalMethods.getCurrentTime());
		msg.setSubject(subject);
		msg.setContent(content);
		msg.setStatus(Constraint.MISSED);
		session.save(msg);
	}	
	

	@Override
	public void receive(SessionFactory sessionFactory, Session session,
			Message msg) {
		msg.setStatus(Constraint.RECEIVED);
		msg.setReceive_date(AdditionalMethods.getCurrentDate());
		msg.setReceive_time(AdditionalMethods.getCurrentTime());
	}

	@Override
	public Message id_to_msg(SessionFactory sessionFactory, Session session,
			int message_id) {
		Object object = session.load(Message.class, message_id);
		Message msg = (Message) object;
		return msg;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Message> list_by_receiver(SessionFactory sessionFactory,
			Session session, int receiver_id) {
		Criteria cr = session.createCriteria(Message.class);
		cr.add(Restrictions.eq("receiver_id", receiver_id));
		cr.addOrder(Order.desc("send_date"));
		cr.addOrder(Order.desc("send_time"));
		return cr.list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Message> list_by_sender(SessionFactory sessionFactory,
			Session session, int sender_id) {
		Criteria cr = session.createCriteria(Message.class);
		cr.add(Restrictions.eq("sender_id", sender_id));
		cr.addOrder(Order.desc("send_date"));
		cr.addOrder(Order.desc("send_date"));
		return cr.list();
	}	

}
